//
//  JLOauthViewController.swift
//  新浪微博
//
//  Created by linlin on 15/11/24.
//  Copyright © 2015年 jilin. All rights reserved.
//

import UIKit
import SVProgressHUD

class JLOauthViewController: UIViewController {
    
    override func loadView() {
        view = webView
        webView.delegate = self
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        //加载授权界面
        let request = NSURLRequest(URL: JLNetworkTool.sharedNetworkTool.oauthURL())
        webView.loadRequest(request)

    
        //设置导航栏
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoFill")
        
         navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        
    }


    //填充账号
    func autoFill() {
        //创建js代码
        let js = "document.getElementById('userId').value='13632450751'; document.getElementById('passwd').value='linlovezhu624898'"
        //让webView执行js代码
        webView.stringByEvaluatingJavaScriptFromString(js)
    }
    
    //取消
    func close() {
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
        
        
    }
    
    
    
    
    //加载accessToken
    func loadAccessToken(code: String) {
        JLNetworkTool.sharedNetworkTool.loadAccessToken(code) { (result, error) -> () in
            if error != nil || result == nil {
                print("\(error)")
                SVProgressHUD.showErrorWithStatus("网络不给力啊", maskType: SVProgressHUDMaskType.Black)
                
                //延迟一秒再退出
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                    self.close()
                })
                return

            }
            
            //如果有数据
            
            let userAccount = JLUserAccount(dict: result!)
            //保存到沙盒
            userAccount.saveAccount()
            
            //移除控制器
            self.close()
            
            AppDelegate.swichViewRootController(false)
            
            print("\(userAccount)")
        }
    }
    
    
    
    
    

    //懒加载
    lazy var webView: UIWebView = UIWebView()
    
    
}


extension JLOauthViewController: UIWebViewDelegate {
    
    //开始加载
    func webViewDidStartLoad(webView: UIWebView) {
        
        SVProgressHUD.showWithStatus("正在拼命加载。。。", maskType: SVProgressHUDMaskType.Black)
    }
    
    //加载完成
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    //加载一个链接时调用，询问是否可以加载
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //获得将要请求的url字符串
        let urlString = request.URL!.absoluteString
        
        //如果没有包含redirect_uri，说明不是授权界面，就加载
        if !urlString.hasPrefix(JLNetworkTool.sharedNetworkTool.redirect_uri) {
            return true
        }
        
        //同意授权会加载url:http://www.example.com/response&code=CODE
        if let query = request.URL?.query{
            let codeString = "code="
            if query.hasPrefix(codeString) {
                //点击了授权
                //截取获得code
                let NSQuery = query as NSString
                let code = NSQuery.substringFromIndex(codeString.characters.count)
                
                
                //加载accessToken
                loadAccessToken(code)
            }else
            {
                print("取消")
                self.close()
            }
        }
        
        
        return false
    }
    
    
    
    
    
    
    
}



